<template>
    <div>
        <!--面包协导航区域-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!--卡片视图-->
        <el-card>
            <!--按钮区-->
            <el-row>
                <el-col>
                    <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
                </el-col>
            </el-row>
            <!-- 角色列表区  border边框线 stripe隔行变色-->
            <el-table
                :data="rolelist" border stripe
                >
                <!--展开列-->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row :class="['bdbottom',i1===0 ? 'bdtop' : '','vcenter']" v-for="(item1,i1) in scope.row.children" 
                        :key="item1.id">
                            <!-- 一级权限-->
                            <el-col :span="5">
                                <el-tag  closable @close="removeRightById(scope.row,item1.id)">
                                    {{item1.authName}}
                                </el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 二级三级权限-->
                            <el-col :span="19">
                                <!--通过 循环 二级权限-->
                                <el-row v-for="(item2,i2) in item1.children" :key="item2.id" :class="['bdbottom',i2===0 ? 'bdtop' : '','vcenter']" >
                                    <!-- 二级权限-->
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">
                                            {{item2.authName}}
                                        </el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <!--三级权限-->
                                    <el-col :span="18">
                                        <el-tag v-for="(item3,i3) in item2.children" :key="item3.id" type="warning" closable 
                                        @close="removeRightById(scope.row,item3.id)"> 
                                            {{item3.authName}}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <!--索引列-->
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column
                    prop="roleName"
                    label="角色名称">
                </el-table-column>
                <el-table-column
                    prop="roleDesc"
                    label="角色描述">
                </el-table-column>
                <el-table-column
                    label="操作"
                    width="300px">
                    <template slot-scope="scope" >
                            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">编辑</el-button>
                            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRoleById(scope.row.id)">删除</el-button>
                            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配角色</el-button>
                    </template>                    
                </el-table-column>
            </el-table>
        </el-card>
        <!--添加角色对话框-->
        <el-dialog
            title="添加角色"
            :visible.sync="addDialogVisible" @close="addDialogClosed"
            width="30%">
            <!--内容主题区-->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="90px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <!--底部区 按键区-->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addRole">确 定</el-button>
            </span>
        </el-dialog>

        <!--修改角色的对话框-->
        <el-dialog
            title="修改角色"
            :visible.sync="editdialogVisible"
            width="50%" @close="editDialogClosed">
            <!--内容主题区-->
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="90px"
            >
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="editForm.roleDesc"></el-input>
                </el-form-item> 
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editdialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editdRoleInfo">确 定</el-button>
            </span>
        </el-dialog>
        <!--分配权限对话框-->
        <el-dialog @close="setRightDialogClosed"
            title="分配权限"
            :visible.sync="setRightdialogVisible"
            width="50%">
            <!--这是一段信息-->
            <el-tree :data="rightsList" :props="treeProps"
             show-checkbox ref="treeRef"
             node-key="id" default-expand-all :default-checked-keys="defkeys"
             >            
            </el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightdialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            //所用角色列表
            rolelist:[],
            //控制权限对话框显示与隐藏
            setRightdialogVisible:false,
            //所有权限数据
            rightsList:[],
            //树形控件属性绑定对象
            treeProps: {
                label:'authName',
                children:'children'    
            },
            //默认选中节点ID值数组
            defkeys:[],
            roleId:'',
            //控制添加角色对话框显示与隐藏
            addDialogVisible:false,
            //修改角色对话框的显示与隐藏
            editdialogVisible:false,
            //添加角色的表单数据
            addForm:{
                roleName:'',
                roleDesc:'',
            },
            //查询到的角色对象信息
            editForm:{
                roleId:"",
                roleName:'',
                roleDesc:'' 
            },
            //添加表单的验证规则对象
            addFormRules:{
                roleName: [
                    {required: true,message:'请输入角色名称',trigger:'blur'},
                    {min:1,max:10,message:'角色名称的长度在1~10个字符之间',trigger:'blur'}
                ]
            },
            //修改表单的验证规则对象
            editFormRules:{
                roleName: [
                    {required: true,message:'请输入角色名称',trigger:'blur'},
                    {min:1,max:10,message:'角色名称的长度在1~10个字符之间',trigger:'blur'}
                ]
            },
            
        }
    },
    created(){
        this.getRolesList()
    },
    methods:{
        //获取所有角色的列表
        async getRolesList(){
            const {data:res} =await this.$http.get('roles')
            if (res.meta.status !==200) {return this.$message.error('获取角色列表失败')}
            this.rolelist=res.data
            console.log(this.rolelist)
        },
        //根据ID删除对应的权限
        async removeRightById(role,rightId){
            //弹框提示是否删除
            const confirmResult =await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).catch(err=>err)
                if (confirmResult !=='confirm'){
                    return this.$message.info('取消删除')
                }
                //console.log('确认删除')
                const {data:res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
                if (res.meta.status !==200){
                    return this.$message.error('删除权限失败')
                }
                role.children=res.data


        },
        //展示分配权限对话框
        async showSetRightDialog(role){
            //获取所有权限数据
            const {data:res} =await this.$http.get('rights/tree')
            if (res.meta.status!==200){return this.$message.error('获取权限列表失败')}
            this.rightsList = res.data
            console.log(this.rightsList)            
            this.roleId=role.id
            //获取三级节点
            this.getLeafKeys(role,this.defkeys)
            this.setRightdialogVisible=true
        },
        //通过递归循环获取角色三级权限ID
        getLeafKeys(node,arr){
            //判断节点是否为三级节点 不包含这个属即为三级节点
            if (!node.children)
            {
                return arr.push(node.id)
            }
            node.children.forEach(item => this.getLeafKeys(item,arr));
        },
        //监听关闭对话框的方法 
        setRightDialogClosed() {
            this.defkeys=[]
        },
        //点击为角色分配权限
        async allotRights(){
            const keys=[
            this.$refs.treeRef.getCheckedKeys(),
            this.$refs.treeRef.getHalfCheckedKeys()]
            const idStr = keys.join(',')
            console.log(keys)

            const{data:res}=await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
            if (res.meta.status !==200) {return this.$message.error('分配权限失败')}
            this.$message.success('分配权限成功')
            this.getRolesList()
            this.setRightdialogVisible = false
        },

        //添加角色
        addRole(){
            this.$refs.addFormRef.validate(async valid=>{
                if (!valid) return
                //发送添加请求
                const {data:res}=await this.$http.post('roles',this.addForm)
                if(res.meta.status!==200){this.$message.error('添加角色失败')}
                this.$message.success('添加角色成功')

                //隐藏添加对话框
                this.addDialogVisible = false

                //获取角色列表
                this.getRolesList()

            })
        },
        //监听添加角色对话框关闭事件
        addDialogClosed(){
            this.$refs.addFormRef.resetFields();
        },
        //监听修改角色修改表单关闭事件
        editDialogClosed(){
            this.$refs.editFormRef.resetFields()
        },
        //显示编辑角色的对话框 
        async showEditDialog(id){
            
            const {data:res} = await this.$http.get('roles/' +id)
            if (res.meta.status !==200){
                return this.$message.error('查询角色失败')
            }
            this.editForm = res.data
            this.editdialogVisible= true
        },
        //修改并提交
        editdRoleInfo(){
            this.$refs.editFormRef.validate(async valid=>{
                if (!valid) return
                //发起添加请求
                const {data:res}=await this.$http.put('roles/'+this.editForm.roleId,
                {roleName:this.editForm.roleName,roleDesc:this.editForm.roleDesc})
                if (res.meta.status!==201){
                    this.$message.error('修改角色失败！')
                }
                
                //隐藏添加角色的对话框
                this.editdialogVisible = false
                //获取数据列表
                this.getRolesList()

                this.$message.success('修改角色成功!')
            })
        },
        //根据ID删除角色信息
        async removeRoleById(id){
            //樟框询问是否删除数据
            const conFirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).catch(err =>{
                    return err
                })
                //如果取消  返回字符串为cancel
                //如果确认，返回confirm
                if (conFirmResult !=="confirm")
                {
                    return this.$message.info('已取消删除')
                }
                const {data:res} = await this.$http.delete('roles/' +id)
                if (res.meta.status !==200){
                    return this.$message.error('删除失败')
                }
               //隐藏添加户的对话框
                this.editdialogVisible = false
                //获取数据列表
                this.getRolesList()

                this.$message.success('删除角色成功!')
        }

        
    }
}
</script>

<style scoped>
.el-tag{
    margin: 7px;
}

.bdtop{
    border-top:1px solid #eee;
}
.bdbottom{
    border-bottom: 1px solid  #eee;
}

.vcenter{
    display: flex;
    align-items: center;
}
</style>